package nzk.hssftemp;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * javax.script.ScriptEngine utility
 *
 * @author N. Zulkarnaen (n.zulkarnaen@gmail.com)
 *         Date: 7/8/13
 *         Time: 4:26 PM
 * @version $Revision: 6 $
 */
public class ScriptUtil {

    private static ScriptEngineManager manager = new ScriptEngineManager();
    private static ScriptEngine engine = manager.getEngineByName("JavaScript");
    private static String script;
    private static String translatedScript;


    final static char[] BREAKERS = {
            '+', '-', '*', '/', '%', '=', '(', ')', '<', '>', '&', '|', ' ', ';'
    };

    public static Set<String> variables;

    private static String var;

    private static boolean isBreaker(char c) {
        for (char b : BREAKERS) {
            if (c == b) return true;
        }
        return false;
    }

    private static void appendVar(char c) {
        if (var == null) {
            var = String.valueOf(c);
        } else {
            var += c;
        }
    }

    public static boolean nan(String s) {
        try {
            Double.parseDouble(s);
            return false;
        } catch (Exception e) {
            return true;
        }
    }

    private static void appendVars() {
        if (var != null && nan(var)) {
            variables.add(var);
        }
        var = null;
    }

    public static Set<String> getVariables() {
        variables = new LinkedHashSet<String>();
        var = null;
        final char[] chars = script.toCharArray();
        for (char c : chars) {
            if (isBreaker(c)) {
                appendVars();
            } else {
                appendVar(c);
            }
        }
        if (var != null && var.length() > 0) {
            appendVars();
        }
        return variables;
    }

    public static void prepareScript(String script) {
        ScriptUtil.script = script;
        translatedScript = script;
        getVariables();
    }

    public static void replaceVariable(String variable, String replacement) {
        translatedScript = translatedScript.replaceAll(variable, replacement);
    }


    public static boolean evalAsBoolean() throws ScriptException {
        return (Boolean) engine.eval(translatedScript);
    }
}
